package de.urlaub.client.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

import de.urlaub.client.VacationClient;
import de.urlaub.client.data.Employee;

public class LoginDialog extends JDialog implements ActionListener
{
	private ArrayList<Employee> employees;
	private VacationClient vacationClient;
	
	private JTextField idField;
	private JTextField pwField;
	
	public LoginDialog(ArrayList<Employee> employees, VacationClient vacationClient)
	{
		this.employees = employees;
		this.vacationClient = vacationClient;
		
		this.setLayout(new GridLayout(0, 2));
		
		this.add(new JLabel("ID"));
		this.idField = new JTextField();
		this.add(idField);
		
		this.add(new JLabel("Passwort"));
		this.pwField = new JTextField();
		this.add(pwField);
		
		JButton loginButton = new JButton("Anmelden");
		loginButton.addActionListener(this);
		this.add(loginButton);

		this.pack();
		this.setResizable(false);
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
	}
	
	public void setVisible(boolean b) 
	{
		super.setVisible(b);
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if (checkLogin())
		{
			LoginDialog.this.dispose();
			if (VacationClient.employeeFrames != null 
					&& VacationClient.employeeFrames.containsKey(getEmployee().getEmployeeId()))
			{
				
			}
			else
			{
				LoginDialog.this.vacationClient.startProgramm(getEmployee());
			}
		}
		else
		{
			System.out.println("Login nicht erfolgreich");
		}
	}
	
	private boolean checkLogin()
	{
		boolean result = false;
		
		Employee employee = getEmployee();
		if (employee != null && employee.getPassword().equals(this.pwField.getText()))
			result = true;
		
		return result;
	}
	
	private Employee getEmployee()
	{
		Employee result = null;
		
		for (Employee employee : employees)
		{
			if (employee.getEmployeeId().equals(this.idField.getText()))
				result = employee;
		}
		
		return result;
	}
}
